package com.nuanshui.framework.keywordFilter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.exception.BizException;
import com.nuanshui.framework.exception.GlobalErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class KeywordFilter {
	
	private Logger log = LoggerFactory.getLogger(getClass());

	private static Map<Object, Object> keysMap = new HashMap<Object, Object>();

	private static final String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】'；：”“’。，、？]①②③④⑤⑥⑦⑧⑨〇";

	public String filterStr(String str) {
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("").replaceAll(" ", "");
	}

	public void init() {
		List<String> txt = initFile2Map();
		log.info(txt.toString());
		addKeywords(txt);
	}

	public void destroy() {
		clearKeywords();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void addKeywords(List<String> keywords) {
		for (int i = 0; i < keywords.size(); i++) {
			String key = keywords.get(i).trim();
			Map nowhash = null;
			nowhash = keysMap;
			for (int j = 0; j < key.length(); j++) {
				char word = key.charAt(j);
				Object wordMap = nowhash.get(word);
				if (wordMap != null) {
					nowhash = (HashMap) wordMap;
				} else {
					HashMap<String, String> newWordHash = new HashMap<String, String>();
					newWordHash.put("isEnd", "0");
					nowhash.put(word, newWordHash);
					nowhash = newWordHash;
				}
				if (j == key.length() - 1) {
					nowhash.put("isEnd", "1");
				}
			}
		}
	}

	/**
	 * 重置关键词
	 */
	public void clearKeywords() {
		keysMap.clear();
	}

	/**
	 * 检查一个字符串从begin位置起开始是否有keyword符合， 如果有符合的keyword值，返回值为匹配keyword的长度，否则返回零
	 * flag 1:最小长度匹配 2：最大长度匹配
	 */
	@SuppressWarnings("rawtypes")
	private int checkKeyWords(String txt, int begin, int flag) {
		Map nowhash = null;
		nowhash = keysMap;
		int maxMatchRes = 0;
		int res = 0;
		int l = txt.length();
		char word = 0;
		for (int i = begin; i < l; i++) {
			word = txt.charAt(i);
			Object wordMap = nowhash.get(word);
			if (wordMap != null) {
				res++;
				nowhash = (HashMap) wordMap;
				if (nowhash.get("isEnd").equals("1")) {
					if (flag == 1) {
						wordMap = null;
						nowhash = null;
						txt = null;
						return res;
					} else {
						maxMatchRes = res;
					}
				}
			} else {
				txt = null;
				nowhash = null;
				return maxMatchRes;
			}
		}
		txt = null;
		nowhash = null;
		return maxMatchRes;
	}

	// /**
	// * 返回txt中关键字的列表
	// */
	// public Set<String> getTxtKeyWords(String txt) {
	// Set set = new HashSet();
	// int l = txt.length();
	// for (int i = 0; i < l;) {
	// int len = checkKeyWords(txt, i, matchType);
	// if (len > 0) {
	// set.add(txt.substring(i, i + len));
	// i += len;
	// } else {
	// i++;
	// }
	// }
	// txt = null;
	// return set;
	// }
	//
	// /**
	// * 返回过滤违禁词后的列表，并且被替换为“*”
	// */
	// public String getFilerWords(String txt) {
	// int l = txt.length();
	// String filterWords = txt;
	// for (int i = 0; i < l;) {
	// int len = checkKeyWords(txt, i, matchType);
	// if (len > 0) {
	// filterWords = filterWords.replaceAll(txt.substring(i, i + len),
	// "*");
	// i += len;
	// } else {
	// i++;
	// }
	// }
	// return filterWords;
	// }

	/**
	 * 仅判断txt中是否有关键字
	 */
	public boolean isContentKeyWords(String txt) {
		if(SysStringUtils.isBlank(txt)){
			return false;
		}
		txt = filterStr(txt);
		for (int i = 0; i < txt.length(); i++) {
			int len = checkKeyWords(txt, i, 1);
			if (len > 0) {
				return true;
			}
		}
		txt = null;
		return false;
	}

	public List<String> initFile2Map() {
		List<String> list = new ArrayList<String>();
		InputStreamReader read = null;
		try {
			String encoding = "utf-8";
			read = new InputStreamReader(KeywordFilter.class.getResourceAsStream("/META-INF/filter_words.txt"), encoding);
			BufferedReader bufferedReader = new BufferedReader(read);
			String lineTxt = null;
			while ((lineTxt = bufferedReader.readLine()) != null) {
				list.add(lineTxt.trim());
			}
		} catch (Exception e) {
			throw new BizException(GlobalErrorCode.INVALID_ARGUMENT, "读取过滤关键字文件出错");
		} finally {
			if(read!=null){
				try {
					read.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return list;
	}

	public static void main(String[] args) {
		KeywordFilter filter = new KeywordFilter();
		List<String> keywords = new ArrayList<String>();// 可以把这个列表变成word.properties文件（包含所有违禁词）
		keywords.add("找小姐");
		filter.addKeywords(keywords);

		String txt = "中国人民找  小   姐少黄色";
		txt = txt.replace(" ", "");
		filter.isContentKeyWords(txt);
		
	}
}